<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划开始" prop="planBeg">
        <el-date-picker clearable
          v-model="queryParams.planBeg"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择计划开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划结束" prop="planEnd">
        <el-date-picker clearable
          v-model="queryParams.planEnd"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择计划结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fitness:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fitness:plan:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划周期" align="center" prop="planCycle">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_date_cycle" :value="scope.row.planCycle"/>
        </template>
      </el-table-column>
      <el-table-column label="周期长度" align="center" prop="cycleNum" />
      <el-table-column label="计划开始日期" align="center" prop="planBeg" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planBeg, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束日期" align="center" prop="planEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEnd, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划内容" align="center" prop="planInfo" />
      <el-table-column label="完成度" align="center" prop="planFinished" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fitness:plan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fitness:plan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改健身计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="90px">
        <el-form-item label="周期长度" prop="cycleNum">
          <el-input-number v-model="form.cycleNum" placeholder="请输入周期长度" :min="1"/>
        </el-form-item>
        <el-form-item label="计划周期" prop="planCycle">
          <el-select v-model="form.planCycle" placeholder="请选择计划周期">
            <el-option
              v-for="dict in dict.type.sys_date_cycle"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="planBeg">
          <el-date-picker clearable
            v-model="form.planBeg"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划开始日期">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="计划内容" prop="planInfo">
          <div>
            <el-button size="mini" type="text" icon="el-icon-plus" @click="addExtraInput">添加一行</el-button>
            <el-popover
                placement="top-start"
                title=""
                width="500"
                trigger="hover">
              <el-alert
                  title="该周期内需训练的部位及每个部位的训练占比"
                  type="info"
                  :closable="false">
              </el-alert>
              <i slot="reference" style="margin-left: 5px" class="el-icon-info"></i>
            </el-popover>
          </div>
          <div v-if="this.extraList && this.extraList.length > 0">
            <el-alert title="" type="info" :closable="false" :show-icon="false">
              <template slot='title'>
                <!--遍历数组，根据不同的结构，展现表单样式、一行单个或者多个输入框，具体看自己实现，这里是一行对应一个键值对-->
                <div v-for="(item,index) in this.extraList" :key="index" style="margin-top: 5px" :v-model="form.planInfo">
                  <el-select placeholder="健身部位" v-model="item.key" @focus="sliderChange()">
                    <el-option
                      v-for="place in placeData" :key="place.value"
                      :label="place.label"
                      :value="place.value"
                      :disabled="place.disabled"
                    ></el-option>
                  </el-select>

                  <div >
                    <span class="demonstration">该周期内占比</span>
                    <!-- <el-slider
                      v-model="item.value"
                      :step="10"
                      @change="sliderChange()">
                    </el-slider> -->
                    <el-radio v-model="item.value" label="3">高</el-radio>
                    <el-radio v-model="item.value" label="2">中</el-radio>
                    <el-radio v-model="item.value" label="1">低</el-radio>
                  </div>
                  <el-button size="mini" type="text" icon="el-icon-delete" style="color: #F56C6C"
                            @click="delExtraInput(index)">删除
                  </el-button>
                </div>
              </template>
            </el-alert>
          </div>
        </el-form-item>
        <el-form-item label="开始日期" prop="planFinished">
          <el-date-picker clearable
            v-model="form.planBeg"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择计划开始日期">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="validForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan, ifExistPlan } from "@/api/fitness/plan";
import { dictBasic, treeBasic } from "@/api/fitness/basic";

export default {
  name: "Plan",
  dicts: ['sys_date_cycle'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 健身计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      max: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCycle: null,
        cycleNum: null,
        planBeg: null,
        planEnd: null,
        planInfo: null,
        planFinished: null
      },
      extraList:[],
      placeData: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        planCycle: [
          { required: true, message: "计划周期不能为空", trigger: "change" }
        ],
        cycleNum: [
          { required: true, message: "周期长度不能为空", trigger: "blur" }
        ],
        planBeg: [
          { required: true, message: "计划开始日期不能为空", trigger: "blur" }
        ],
        createUser: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询健身计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      dictBasic(this.queryParams).then(response => {
        this.typeData = response.type_map;
        this.unitData = response.unit_map;
      });
      treeBasic(this.queryParams).then(response => {
       this.placeData = response
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        planCycle: null,
        cycleNum: null,
        planBeg: null,
        planEnd: null,
        planInfo: null,
        createUser: null,
        createTime: null,
        planFinished: null,
        planPriority: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加健身计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids
      getPlan(planId).then(response => {
        this.form = response.data;
        this.extraList = this.form.planInfo;
        this.open = true;
        this.title = "修改健身计划";
      });
    },
    /** 校验按钮（校验是否存在周期内其他计划，计算优先级） */
    validForm() {
      var count;
      var bool = true;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.extraList.length == 0) {
            this.$modal.alertWarning("请至少填写一项计划");
          } else {
            for (let item of this.extraList) {
              if (item.key == "") {
                this.$modal.alertWarning("请补全健身部位");
                bool = false;
              }
            }
            if (bool == true) {
              this.form.planInfo = JSON.stringify(this.extraList);
              ifExistPlan(this.form).then(response => {
                count = response;
                if (count != 0) {
                  this.$modal.confirm('周期内已存在其他计划，是否优先执行当前计划').then(() => {
                    this.submitForm(count + 1);
                  }).catch((e) => {
                    if (e == 'cancel') {
                      this.submitForm(count - 1);
                    }
                  });
                } else {
                  // 标准值是50，方便加减判断优先级
                  this.submitForm(50);
                }
              });
            }
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm(count) {
      // 设置优先级
      this.form.planPriority = count;
      this.form.planInfo = JSON.stringify(this.extraList);
      if (this.form.planId != null) {
        updatePlan(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addPlan(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除健身计划编号为"' + planIds + '"的数据项？').then(function() {
        return delPlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fitness/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    },
    addExtraInput() {
      this.extraList.push({'key': '','value': '2'})
    },
    /** 根据数组索引删除一行键值对 */
    delExtraInput(index) {
      this.extraList.splice(index, 1);
    },
    /** 将参数列表提取出来 转换为对象形式 */
    extraListToData() {
      let extraList = this.extraList;
      if (!extraList || extraList.length < 1) {
        return {};
      }
      let extraData = new Map();
      for (let item of extraList) {
        let key = item.key;
        let value = item.value;
        if (key && value) {
          extraData[key] = value;
          // extraData.set(key,value);
        }
      }
      return extraData;
      // return JSON.stringify(extraData);
    },
    sliderChange() {
      for(var places of this.placeData) {
        places.disabled = false;
        for (let item of this.extraList) {
          if (places.value == item.key) {
            places.disabled = true;
          }
        }
      }
    }
  }
}
</script>
